' *** Documentation
' 
' Klenwell VB Script Template
' 
' last updated: Jun 2007
' author: klenwell@gmail.com
' 
' DESCRIPTION
' 	automates file includes and error handling for vbscripts 
' 
' NOTES
' 	See http://www.klenwell.net/is/CategoryVbScript
' ____________________________________________________________________________*/


' *** Pre-Script (error handling, file includes)
' ____________________________________________________________________________*/

Option Explicit

' Set Files to Include Here
dim aINCLUDE(5)
aINCLUDE(1) = "inc1.vbs"
aINCLUDE(2) = "inc2.vbs"

' Show Errors?
Const SHOW_ERRORS = True

' *** SCRIPT ERROR HANDLER
' Config
dim oDictErr, iErrCount
Set oDictErr = CreateObject("Scripting.Dictionary")
iErrCount = 0

' Klenwell Error Trigger
Function kwTriggerError(sMessage)
	iErrCount = iErrCount + 1
	oDictErr.Add iErrCount, sMessage
	If SHOW_ERRORS Then: MsgBox("Error #" & iErrCount & " : " & sMessage)
	Err.Clear()
End Function

' Klenwell Error Dump
Sub kwDumpErrors
	dim sOut, sKey
	sOut = "Error Dump ("&iErrCount&" Errors): " & VbCrLf
	For Each vKey In oDictErr
		sOut = sOut & "Error " & vKey & " in oDictErr: " & oDictErr.Item(vKey) & VbCrLf
	Next
	MsgBox(sOut)
End Sub
' *** END SCRIPT ERROR HANDLER


' *** FILE INCLUDE HANDLER
' include file
Function kwIncludeFile(sFilePath)
	On Error Resume Next
	dim oFsoInc, oFileHandler, sIncContent
	Set oFsoInc = CreateObject ("Scripting.FileSystemObject")
	
	If sFilePath = "" Then: Exit Function: End If
	
	If NOT oFsoInc.FileExists(sFilePath) Then
		kwTriggerError("unable to load " & sFilePath & " : file not found")
		Exit Function
	End If
	
	Set oFileHandler = oFsoInc.OpenTextFile(sFilePath,1)
	If Err.number <> 0 Then
		kwTriggerError("file " & sFilePath & " could not be opened")
		Exit Function
	End If
	
 	sIncContent = oFileHandler.ReadAll
 	oFileHandler.close
 	ExecuteGlobal sIncContent

	Set oFsoInc = Nothing
	Set oFileHandler = Nothing

End Function

' include all files
Sub kwIncludeFiles
	dim sFile
	For Each sFile In aINCLUDE
		kwIncludeFile(sFile)
	Next
End Sub

Call kwIncludeFiles

' ============================================================================*/


